package com.ettractions.kiosk.mediators
{
	import com.ettractions.kiosk.components.CategoryMenu;
	import com.ettractions.kiosk.events.BrochureSelectedEvent;
	import com.ettractions.kiosk.events.KioskModelEvent;
	import com.ettractions.kiosk.events.SelectCategoryEvent;
	import com.ettractions.kiosk.models.KioskModel;
	import com.ettractions.kiosk.vo.CategoryVO;
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayList;
	
	import org.robotlegs.mvcs.Mediator;
	
	import spark.components.List;
	import spark.events.IndexChangeEvent;
	
	public class CategoryMenuMediator extends Mediator
	{
		[Inject]
		public var model:KioskModel;
		
		[Inject]
		public var view:CategoryMenu;

		override public function onRegister():void
		{
			eventDispatcher.addEventListener(KioskModelEvent.UPDATED, handleKioskModelUpdated);			
			eventDispatcher.addEventListener(BrochureSelectedEvent.BROCHURE_SELECTED, handleBrochureSelected);
			
			view.homeButton.addEventListener(MouseEvent.CLICK, handleHomeButtonClick);
				
			view.list.addEventListener(IndexChangeEvent.CHANGE, handleListIndexChange);
		}
		
		private function handleKioskModelUpdated(event:KioskModelEvent):void
		{
			var dataProvider:ArrayList = new ArrayList();
			
			for each (var category:CategoryVO in model.categories)
				dataProvider.addItem(category);
				
			view.list.dataProvider = dataProvider;
			
			view.homeButton.label = model.title;
			
			eventDispatcher.removeEventListener(KioskModelEvent.UPDATED, handleKioskModelUpdated);
		}
		
		private function handleBrochureSelected(event:BrochureSelectedEvent):void
		{
			view.list.selectedIndex = event.category == null
			                        ? -1
			                        : view.list.dataProvider.getItemIndex(event.category);
		}
		
		private function handleHomeButtonClick(event:MouseEvent):void
		{
			eventDispatcher.dispatchEvent(new SelectCategoryEvent(SelectCategoryEvent.SELECT_CATEGORY, null));
		}
		
		private function handleListIndexChange(event:IndexChangeEvent):void
		{
			if (event.newIndex > -1)
			{
				eventDispatcher.dispatchEvent(new SelectCategoryEvent(SelectCategoryEvent.SELECT_CATEGORY, CategoryVO(view.list.dataProvider.getItemAt(event.newIndex))));				
			}
		}
	}
}